# encoding:utf-8
import os
import pandas as pd
from flask import render_template
from flask_login import login_required
from flask_login import current_user
from flask import request
from werkzeug.exceptions import abort
from apps import config
from apps.blueprint import view
from apps.user.process.permissions import permission_required
import util.xtool as xtool
import util.dbcom as dbcom
import apps.adog.viewPoint as vp
# import sys
# sys.path.append('..')
import xconfig as C
import re

__author__ = "adog"


@view.route('/', methods=['GET', 'POST'])
def index():
    return render_template('/index.html')


@view.route('/NoPermission', methods=['GET', 'POST'])
def noPermission():
    # return render_template('index.html')
    return ' NoPermission'


def getViewPoints(cloneKey=''):
    viewPnt = vp.ViewPoint()
    viewPnt.loadTVChart()
    notes = viewPnt.notes
    noteStr = '<form method="POST" name = "viewPoints">'
    if len(notes) > 0: 
        for i in notes.index:
            ownerId = notes.loc[i, 'ownerId']
            chartName = notes.loc[i, 'chartName']
            note = notes.loc[i, 'note'] 
            # http = re.search("(?P<url>https?://[^\s]+)", note).group("url").split(']')[0]
            
            symbol = notes.loc[i, 'symbol'] 
            resolution = notes.loc[i, 'resolution'] 
            cloneText = "克隆图"
            if cloneKey == ownerId + '_' + chartName + '_' + symbol.split(':')[-1] + "_" + resolution:
                cloneText = "已经克隆"
            
            lastUpdateTime = notes.loc[i, 'lastUpdateTime'] 
            '''
            noteStr = noteStr + '<br>' + '&nbsp;' + \
                    '<span name="ownerId" values="' + ownerId + '" style="font-size: 13px;color: rgb(0, 128, 192);"> <strong>' + ownerId + ' </strong></span>' + \
                    '<span name="chartName" style="font-size:10px;color: rgb(128, 0, 64);">&nbsp;&nbsp;[' + chartName + '&nbsp;&nbsp;] <button name="select" style="width:80px;height:30px;font-size:8px;color: rgb(32,32, 32);" value="' + ownerId + '_' + chartName + '_' + symbol.split(':')[-1] + "_" + resolution + '">' + cloneText + '</button><br>' + \
                    '&nbsp;&nbsp;' + symbol + ",&nbsp;" + resolution + ",&nbsp;" + lastUpdateTime + "</span>" + \
                    '&nbsp;<div style="height:95%;width: 98%;font-size: 12px;BORDER-BOTTOM: 0px solid; BORDER-LEFT: 0px solid; BORDER-RIGHT: 0px solid; BORDER-TOP: 1px">' + \
                    note + '</div>'
            '''
            noteStr = noteStr + '<br>' + \
                    '<span name="ownerId" values="' + ownerId + '" style="font-size: 13px;color: rgb(0, 128, 192);"> <strong>' + ownerId + ' </strong></span>' + \
                    '<span name="chartName" style="font-size:10px;color: rgb(128, 0, 64);">&nbsp;&nbsp;[' + chartName + '&nbsp;&nbsp;] <button name="select" style="width:80px;height:30px;font-size:8px;color: rgb(32,32, 32);" value="' + ownerId + '_' + chartName + '_' + symbol.split(':')[-1] + "_" + resolution + '">' + cloneText + '</button><br>' + \
                    symbol + ",&nbsp;" + resolution + ",&nbsp;" + lastUpdateTime + "</span>" + \
                    '&nbsp;<br><span style="font-size:11px;">' + note + '<span>'
    noteStr = noteStr + '</form>'
    
    return notes, noteStr


@view.route('/tv', methods=['GET', 'POST'])
@login_required
def tv():
    if xtool.nowTime() >= '2022-12-26 10:00':
        return render_template('/adog/outdue.html')
   
    alert_tbl = ''
    top_att_tbl = ''
    top_cp_tbl = ''
    viewPoint = ''
    noteStr = ''
    notes = None
    if C.isUseMemo:
        import apps.adog.memo as MEMO
        
        mm = MEMO.Memo(current_user.username)
        
        if len(mm.tvData) > 0:
            try:
                keyPrice = mm.getKeyPrices(isSetMultiIndex=False)
                keyPrice['textAlarm'] = ['<span style="background-color: rgb(255, 0, 0);">%s</span>' % (keyPrice.loc[i, 'text']) if keyPrice.loc[i, 'alarm'] == 1 else keyPrice.loc[i, 'text'] for i in keyPrice.index]
                text = keyPrice.groupby(by=['chartName', 'symbol'])['textAlarm'].apply(list).reset_index()
                alert_tbl = xtool.getHtml(text, align='left').replace('\n', '').replace('&lt;', '<').replace('&gt;', '>')
            
                top_att = mm.getAttLast(keyword='', sortBy='att', top=3)[['chartName', 'symbol', 'att', 'marginRate']]
                top_att_tbl = xtool.getHtml(top_att, align='left').replace('\n', '').replace('&lt;', '<').replace('&gt;', '>')
                
                top_cp = mm.getAttLast(keyword='', sortBy='cp', top=3)[['chartName', 'symbol', 'cp', 'marginRate']]
                top_cp_tbl = xtool.getHtml(top_cp, align='left').replace('\n', '').replace('&lt;', '<').replace('&gt;', '>')
            
            except Exception as e:
                print(e)
    
    if request.method == "GET":
        if C.isShowViewPoint:
            notes, noteStr = getViewPoints()
        return render_template('/tv.html',
                               alert_tbl=alert_tbl,
                               top_att_tbl=top_att_tbl,
                               top_cp_tbl=top_cp_tbl,
                               host=C.tvBackend_host,
                               addWindow=C.addWindow,
                               notes=noteStr)
    elif request.method == "POST": 
        rs = request.form
        select = rs['select']
        ownerId, chartName, symbol, resolution = select.split('_')
        
        sql = ' replace into model_chart(ownerSource,ownerId,content,lastModified,name,resolution,symbol,cloneOther) \
                 (select ownerSource, "%s" as ownerId, content, lastModified,concat(name,"(from %s)"),resolution, symbol,"%s" as cloneOther from model_chart '\
                'where ownerId="%s" and name="%s" and symbol="%s" and resolution="%s");' % \
                ((str(current_user.username), ownerId, ownerId, ownerId, chartName, symbol, resolution))
        
        dbcom.excute(sql)
        
        if C.isShowViewPoint:
            notes, noteStr = getViewPoints(cloneKey=select)
        return render_template('/tv.html',
                               alert_tbl=alert_tbl,
                               top_att_tbl=top_att_tbl,
                               top_cp_tbl=top_cp_tbl,
                               host=C.tvBackend_host,
                               addWindow=C.addWindow,
                               notes=noteStr)


@view.route('/test', methods=['GET', 'POST'])
def test():
    return render_template('/test.html')


@view.route('/test2', methods=['GET', 'POST'])
def test2():
    return render_template('/test2.html')


# 通用视图函数
@view.route('/<path:path>', methods=['GET', 'POST'])
def pages(path):
    absolute_path = os.path.abspath("{}/{}/{}.html".format(os.path.dirname(__file__), view.template_folder, path))
    if not os.path.isfile(absolute_path):
        abort(404)
    return render_template('{}.html'.format(path))


# 所有以user开头的页面都会跑这里了
@view.route('/user/<path:path>', methods=['GET', 'POST'])
@login_required
def user_pages(path):
    path = "/user/{}".format(path)
    absolute_path = os.path.abspath("{}/{}/{}.html".format(os.path.dirname(__file__), view.template_folder, path))
    if not os.path.isfile(absolute_path):
        abort(404)
    return render_template('{}.html'.format(path))


# 所有以admin开头的页面都会跑这里了
# permission_required限制至少Admin以上权重的用户才能访问
@view.route('/admin/<path:path>', methods=['GET', 'POST'])
@login_required
@permission_required(config.Role.ADMIN)
def admin_pages(path):
    path = "/admin/{}".format(path)
    absolute_path = os.path.abspath("{}/{}/{}.html".format(os.path.dirname(__file__), view.template_folder, path))
    if not os.path.isfile(absolute_path):
        abort(404)
    return render_template('{}.html'.format(path))
